<template>
    <d2-container>
        <el-main>

<!--            <h3>手机号</h3>-->
<!--            <el-input placeholder="请输入手机号" v-model="cellphone" :disabled="disabled"></el-input>-->


<!--             <h3>性别</h3>
            <template>
                <el-radio v-model="gender" label="0" value=0>男{{gender}}</el-radio>
                <el-radio v-model="gender" label="1" value=1>女</el-radio>
            </template> -->


            <h3 v-if='headquarter'>选择校区</h3>

            <el-select v-if='headquarter'
                                    v-model="school"
                                    filterable
                                    placeholder="请选择校区">
                                <el-option
                                        v-for="item in schools"
                                        :key="item._id"
                                        :label="item.name"
                                        :value="item._id"
                                ></el-option>
                            </el-select>


           <!--  <el-checkbox-group v-model="school">
                <el-checkbox v-for="value in schools" :label="value._id" :key="value._id">{{value.name}}</el-checkbox>
            </el-checkbox-group> -->


<!--            <h3>用户姓名</h3>-->
<!--            <el-input placeholder="请输入姓名" v-model="username" :disabled="disabled"></el-input>-->


<!--            <h3>邮箱</h3>-->
<!--            <el-input placeholder="请输入邮箱" v-model="email" :disabled="disabled"></el-input>-->



<!--            <h3>微信</h3>-->
<!--            <el-input placeholder="请输入微信id" v-model="wechat" :disabled="disabled"></el-input>-->


<!--             <h3>身份</h3>
            <el-radio-group v-model="roleDefault" @change="setRoles">
                <el-radio v-for="value in rolesDefault" :label="value.name" :key="value._id">{{value.name}}</el-radio>
            </el-radio-group> -->

            <h3>权限</h3>
            <el-checkbox-group v-model="role">
                <el-checkbox v-for="value in roles" :label="value._id" :key="value._id">{{value.name}}</el-checkbox>
            </el-checkbox-group>



            <h3>绑定员工账号</h3>
            <el-button
                    @click="selectStaff = true"
                    style="float:left;margin:10px"
                    icon="el-icon-plus"
                    size="small"
                    type="primary"
                    :disabled="disabled"

            >选择要绑定的员工(也可以之后绑定)</el-button>

            <el-dialog title="员工" :visible.sync="selectStaff">
                <el-input placeholder="请输入员工姓名" v-model="searchStaffName" size="small">
                    <el-button slot="append" icon="el-icon-search" @click="searchStaff"></el-button>
                </el-input>
                <el-table :data="staffList">
                    <el-table-column property="name" label="员工姓名"></el-table-column>
                    <el-table-column fixed="right" label="操作">
                        <template slot-scope="scope">
                            <el-button @click="addStaff(scope.row)" type="text">选择</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <el-pagination small layout="prev, pager, next" :total="searchStaffCount" @current-change="staffCurrentChange"></el-pagination>
            </el-dialog>
            <el-table :data="selectedStaffList" border style="width: 100%">
                <el-table-column prop="name" label="员工姓名"></el-table-column>
                <el-table-column fixed="right" label="操作">
                    <template slot-scope="scope">
                        <el-button @click="deleteStaffClick(scope.$index)" type="text" size="small" :disabled="disabled">删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>




            <h3>qq</h3>
            <el-input placeholder="请输入qq" v-model="qq" :disabled="disabled"></el-input>


            <h3>用户名</h3>
            <el-input placeholder="请输入用户昵称" v-model="username" :disabled="disabled || ((username == 'root') && (id != undefined))" ></el-input>

            <h3>密码</h3>
            <el-input placeholder="请输入密码" v-model="verified" :disabled="disabled" show-password></el-input>



        </el-main>
        <el-footer>
            <el-button type="primary" @click="submit">提交</el-button>
            <el-button @click="edit" v-show="editShow">修改</el-button>
        </el-footer>
    </d2-container>
</template>

<script>
    import request from "@/plugin/axios";
import { mapState } from "vuex";

    export default {
        data() {
            return {
                editShow: false,
                disabled: false,
                id : undefined,
                // cellphone: undefined,
                gender: undefined,
                room: undefined,
                // email: undefined,
                // wechat: undefined,
                qq: undefined,
                username: undefined,
                verified: undefined,
                rolesDefault:[],
                roles: [],
                role: [],
                schools:[],
                school:undefined,
                roleDefault:undefined,
                selectStaff:false,
                searchStaffName:undefined,
                staffList:undefined,
                searchStaffCount:undefined,
                selectedStaffList:[],
                staff:undefined,
                headquarter : false


            };
        },
          computed:{
    ...mapState('d2admin/user',['info'])
  },

        methods: {
            searchStaff() {
                this.getStaffList(1);
            },
            getStaffList(page) {
                request({
                    url: "/staff/getStaffList",
                    method: "post",
                    data: {page: page, pageSize: 10, name: this.searchStaffName,school:this.school}
                }).then(res => {
                    (this.staffList = res.data.staff),
                        (this.searchStaffCount = res.data.total);

                });
            },
            addStaff(e){
                if(this.selectedStaffList.map(event =>{return event._id}).indexOf(e._id) == -1){
                    this.selectedStaffList = []
                    this.selectedStaffList.push(e)
                    this.staff = e._id
                }else{
                    this.$message({
                        showClose: true,
                        message: '已经添加这个经办人了哦',
                        type: 'error'
                    });
                }
            },
            staffCurrentChange(e) {
                this.getStaffList(e);
            },
            deleteStudentClick(e){
                this.selectedStaffList = []
                this.staff = undefined
            },

            submit() {
                let data = {};
                data.gender = this.gender
                let url = "/user/userRegister";
                let title = "新建用户成功"
                if (this.id != undefined) {
                    data.id = this.id;
                    url = "/user/updateUser";
                    title = "用户修改成功"
                }
                data.qq = this.qq
                data.username = this.username
                data.verified = this.verified
                data.role = this.role
                data.school = [this.school]
                data.staff = this.staff
                request({
                    url: url,
                    method: "post",
                    data
                }).then(res => {
                    
                    if (res.code == 200) {
                        this.refresh = true
                        
                        this.$alert("", title, {
                            confirmButtonText: "确定"
                        });
                        this.gender = undefined
                        this.room = undefined
                        this.qq = undefined
                        this.username = undefined
                        this.verified = undefined
                        this.role = []
                        this.school = []
                        this.staff = undefined
                        this.selectedStaffList = []
                        this.$router.push({path:"/user-list"})
                    }
                    // 返回数据
                });
            },
            edit() {
                this.disabled = false;
            },

            deleteStaffClick(){
                this.staff = undefined
                this.selectedStaffList = []
            },

            getRoleList() {
                request({
                    url: "/role/getRoleList",
                    method: "post",
                }).then(res => {
                    let temp = []
                    res.data.role.forEach((value, index) => {
                        if (value.name === 'root') {
                            // console.log('ahahah',this.info.school[0])
                             if ((this.info.school[0].headquarter == 1) ){
                                // console.log('enter')
                                temp.push(value)
                                // value.name = 'root'
                                // this.rolesDefault.push(value)
                             }
                        } 
                        else if (value.name != 'school' && value.name != 'teacher' && value.name != 'root') {
                            if (value.name == '总部管理中心'){
                                if ((this.info.school[0].headquarter == 1) ){
                                    temp.push(value)
                                }
                                
                            }
                            else{
                                temp.push(value)
                            }
                            
                        } else {
                            if (value.name == 'school'){
                                if (this.info.school[0].headquarter != 1){
                                    value.name = '校长'
                                    this.rolesDefault.push(value)
                                }
                            }
                            else{
                                // this.rolesDefault.push(value)
                            }
                            
                        }
                    })
                    this.rolesDefault.push({name: '自定义', _id: '77777'})
                    this.roles = temp.filter(e=>{return e.name != '日志记录'})
                    // this.roles = temp

                })
            },

            getSchoolList() {
                request({
                    url: "/school/getSchoolList",
                    method: "post",
                    data: {page: 1, pageSize: 99999}
                }).then(res => {

                    if ((this.info.school[0].headquarter == 1) || (this.info.school[0].headquarter == 2)){
                           this.schools = res.data.school
                        }
                        else{
                            const ak = this.school
                            this.schools = res.data.school.filter(function(e){return e._id == ak})
                        }
                    
                })
            },

            getUser() {
                request({
                    url: "/user/getUser",
                    method: "post",
                    data: {id: this.id}
                }).then(res => {
                   this.role = res.data.role
                   this.school = res.data.school[0]
                   this.username = res.data.username
                   this.verified = ''
                   this.staff = res.data.staff == undefined ? undefined : res.data.staff._id
                   if (this.staff != undefined){
                    this.selectedStaffList = [res.data.staff]
                   }
                   
                   this.gender = res.data.gender
                   this.email = res.data.email
                   this.qq = res.data.qq
                   if (this.username == 'root'){
                        this.headquarter = false
                   }
                   this.getRoleList();
                this.getSchoolList()
                    
                })
            },
            setRoles() {
                let defaultRule = this.roleDefault;
                switch (defaultRule) {
                    // case 'teacher': {

                    //     this.role = [];

                    //     this.roles.forEach((value) => {

                    //     })

                    //     break;
                    // }

                    case '校长': {

                        this.role = [];
                        this.roles.forEach((value) => {
                            this.role.push(value._id)

                        })



                        break;
                    }

                    case '总校长': {
                        this.role = [];
                        this.roles.forEach((value) => {
                            this.role.push(value._id)
                        })

                        break;
                    }

                    default : {
                        this.role = [];
                        this.roles.forEach((value) => {

                            if (value.name === '首页') {
                                this.role.push(value._id)
                            }

                        })
                        break;
                    }
                }


            }

        },
beforeRouteLeave(to,from,next){
        if (this.refresh){
          to.meta.refresh = 'a'
          this.refresh = undefined
        }
        if (this.$route.query.id == undefined){
            from.meta.keep = true
            from.meta.verified = this.verified
            from.meta.role = this.role
            from.meta.gender = this.gender
            from.meta.username = this.username
            from.meta.staff = this.staff
            from.meta.school = this.school
            from.meta.qq = this.qq
            from.meta.selectedStaffList = this.selectedStaffList

        }

        next()
        },
        beforeRouteEnter(to,from,next){
            if (to.meta.keep){
                to.meta.keep = undefined
                next(v=>{
                    v.verified = to.meta.verified
                    v.role = to.meta.role
                    v.gender = to.meta.gender
                    v.username = to.meta.username
                    v.staff = to.meta.staff
                    v.school = to.meta.school
                    v.qq = to.meta.qq
                    v.selectedStaffList = to.meta.selectedStaffList
                    to.meta.verified = undefined
                    to.meta.roles = undefined
                    to.meta.gender = undefined
                    to.meta.username = undefined
                    to.meta.staff = undefined
                    to.meta.school = undefined
                    to.meta.qq = undefined
                    to.meta.selectedStaffList = undefined
                })
            }
            else{
                next()
            }
        },

        created() {
            this.school = this.info.school[0]._id
            
            if (this.$route.query.id != undefined){
                this.id = this.$route.query.id
                this.getUser()
            }
            else{
                this.getRoleList();
                this.getSchoolList()
            }
           if ((this.info.school[0].headquarter == 1) || (this.info.school[0].headquarter == 2)){
                                    this.headquarter = true
                                }


        }
    };
</script>
